﻿using System;
using System.Buffers;
using System.IO;
using OdaOperation.Core;
using OdaOperation.DB;
using OdaOperation.Service;
using Teigha.Core;
using Teigha.TD;

namespace OdaOperation
{
    public class DbOperation
    {
        private MemoryManager m_manger;

        private MemoryTransaction m_startTrans;

        private ExHostAppServices m_hostApp;

        public ExHostAppServices HostApp => m_hostApp;

        public static void Init()
        {
        }

        public void InitOda()
        {
            m_manger = MemoryManager.GetMemoryManager();
            m_startTrans = m_manger.StartTransaction();
            SystemServices pSystemServices = new SystemServices();
            TD_Db.odInitialize(pSystemServices);
            Globals.odgsInitialize();
            Globals.odgiInitialize();
            m_hostApp = new HostAppServices();
            OdaGlobal.LoadModel();
        }

        public DbDatabase ReadFile(string filePath)
        {
            try
            {
                return new DbDatabase(m_hostApp.readFile(filePath));
            }
            catch (Exception ex)
            {
                throw new Exception("文件打开异常" + filePath + ":" + ex.Message);
            }
        }

        public DbDatabase CreateFile()
        {
            return new DbDatabase(m_hostApp.createDatabase(createDefault: true, MeasurementValue.kMetric));
        }

        public void UnInitOda()
        {
            OdaGlobal.UnLoadModel();
            m_manger.StopTransaction(m_startTrans);
            Globals.odgiUninitialize();
            Globals.odgsUninitialize();
            TD_Db.odUninitialize();
        }

        public static void UnInit()
        {
        }

        public static void StartOda(string refPath, Action<DbDatabase> ac, string comPath = null)
        {
            DbOperation dbOperation = new DbOperation();
            dbOperation.InitOda();
            DbDatabase obj = (File.Exists(refPath) ? dbOperation.ReadFile(refPath) : dbOperation.CreateFile());
            ac(obj);
            dbOperation.UnInitOda();
        }
    }
}